﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraGrid.Views.Grid;
using MECPSDB.DatabaseSpecific;
using MECPSDB.EntityClasses;
using MECPSDB.HelperClasses;
using MECUITMPLTLIB;
using Pipo.AeExtensions;
using SD.LLBLGen.Pro.ORMSupportClasses;

namespace MEC.WMS.Template
    {
    public partial class VwFrm:VwFrmUiTemplate
        {
        
        public VwFrm(string cs, string branchcode, string usercode)
            {
            if (cs == null) throw new ArgumentNullException("cs");
            if (usercode == null) throw new ArgumentNullException("usercode");
            this.Cs = cs;
            this.Branchcode = branchcode;
            this.Usercode = usercode;
            InitializeComponent();
            Text = ConsFrmCaption;
        }
        public override sealed string Text { get { return base.Text; }
            set { base.Text = value; } }
        
#region "Overriden Events"



        public override void BtnnewItemClick(object sender,DevExpress.XtraBars.ItemClickEventArgs e)
            {
            MethodAddNew();
            }

        public override void BtnviewItemClick(object sender,DevExpress.XtraBars.ItemClickEventArgs e)
            {
            MethodOpenRecord(gridView1);
            }

        public override void BtndeleteItemClick(object sender,DevExpress.XtraBars.ItemClickEventArgs e)
            {
            MethodDeleteRecord();
            }

        public override void BtnvoidItemClick(object sender,DevExpress.XtraBars.ItemClickEventArgs e)
            {
            MethodVoidRecord();
            }

        public override void BtncloseItemClick(object sender,DevExpress.XtraBars.ItemClickEventArgs e)
            {
            MethodFormClose();
            }

        public override void BtnexporttoexcelItemClick(object sender, ItemClickEventArgs e){
            throw new NotImplementedException();
        }

        public override void BtnexporttowordItemClick(object sender, ItemClickEventArgs e){
            throw new NotImplementedException();
        }

        public override void VwFrmUiTemplateLoad(object sender, EventArgs e){
            MethodLoad();
        }
        
        public override void VwFrmUiTemplateShown(object sender, EventArgs e){
            MethodFormShown();
        }

        public override void VwFrmUiTemplateFormClosed(object sender, FormClosedEventArgs e){
            MethodFormClosed();
        }
        
        public override void VwFrmUiTemplateFormClosing(object sender, FormClosingEventArgs e){
            MethodFormClosing();
        }



        #endregion

#region "Private Methods"
        private void MethodFormClosed(){
            
        }
        private void MethodFormClosing(){
            
        }
        private void MethodFormShown(){
            MethodRefresh();
        }
        private void MethodFormClose()
            {
            Close();
            }
        private void MethodLoad(){
            
        }

#endregion

        private void GridView1DoubleClick(object sender,EventArgs e)
            {
            MethodOpenRecord((GridView) sender);
            }
        private void BackgroundWorker1DoWork(object sender,DoWorkEventArgs e){
        MethodFetchWork(e);
        }
        private void BackgroundWorker1RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e){
            MethodFetchWorkCompleted(e);
        }
        private  void BackgroundWorker1ProgressChanged(object sender,ProgressChangedEventArgs e)
            {
            MessageBox.Show(@"string");
            }


        protected override void MethodRefresh(){
            if (backgroundWorker1.IsBusy){
                btnrefresh.Enabled = false;
                return;
            }
            pictureEdit1.Visible = true;
            pictureEdit1.Image = Properties.Resources.circlethickboxgreen;
            entityCollectionNonGeneric1.Clear();
            backgroundWorker1.RunWorkerAsync(entityCollectionNonGeneric1.EntityFactoryToUse);

        }
        private void MethodFetchWork(DoWorkEventArgs e){
            

            IEntityFactory2 entityFactoryToUse = (IEntityFactory2) e.Argument;
            EntityCollection ec;
            
            ////TODO Fetch Parameters Needed Here
            IRelationPredicateBucket filter = new RelationPredicateBucket();
            ISortExpression sortClauses = null;
            IPrefetchPath2 prefetchPath = null;
            ExcludeIncludeFieldsList excludedFields = new ExcludeIncludeFieldsList(true);
            ////TODO Fetch Parameters Needed Here
            using (DataAccessAdapter dataAccessAdapter = new DataAccessAdapter(Cs)){
                ec = new EntityCollection();
                ec.EntityFactoryToUse = entityFactoryToUse;
                dataAccessAdapter.FetchEntityCollection(ec, filter, 0, sortClauses, prefetchPath, excludedFields);
            }
            e.Result = ec;
        }
        private void MethodFetchWorkCompleted(RunWorkerCompletedEventArgs e){
            try{
                if (e.Cancelled) return;
                if (e.Error != null) return;
                if (e.Result == null) return;
                EntityCollection entityCollection  = (EntityCollection) e.Result;
                foreach (EntityBase2 entityBase2 in entityCollection){
                    entityCollectionNonGeneric1.Add(entityBase2);
                }

            } catch (Exception ex){
                MessageBox.Show(ex.Message);
            }finally{
                pictureEdit1.Image = null; 
                pictureEdit1.Visible = false; 
                btnrefresh.Enabled = true;
            }
        }



        private void MethodAddNew(){
            using (AeFrm aeFrm = new AeFrm(Cs, Branchcode, Usercode)){
                AeReturnvalue aeReturnvalue = aeFrm.ShowmetoAdd();
                if (aeReturnvalue.Cancelled) return;
                if (aeReturnvalue.Rowdata == null) return;
                entityCollectionNonGeneric1.Add((EntityBase2) aeReturnvalue.Rowdata);
            }
        }
        private void MethodOpenRecord(GridView gridview){
            if (gridview.SelectedRowsCount == 0) return;
            if (gridview.SelectedRowsCount > 1) return;
            if (gridview.SelectedRowsCount != 1) return;

            int selectedrowCollectionindex = gridview.GetDataSourceRowIndex(gridview.GetSelectedRows()[0]);
            EntityBase2 a = entityCollectionNonGeneric1[selectedrowCollectionindex];
                using (AeFrm aeFrm = new AeFrm(Cs,Branchcode, Usercode)){
                    AeReturnvalue aeReturnvalue = aeFrm.ShowmetoEdit(a.Fields.PrimaryKeyFields[0].CurrentValue);
                    if (aeReturnvalue.DalOpeningError) return;
                    if (aeReturnvalue.Rowdata == null) return;
                    entityCollectionNonGeneric1[selectedrowCollectionindex] = (EntityBase2) aeReturnvalue.Rowdata;
                    return;
                }


        }
        private void MethodVoidRecord()
            {
            MessageBox.Show(@"Not Implemented.");
            }

        private void MethodDeleteRecord(){
            GridView gridview = gridView1;
            if (gridview.SelectedRowsCount == 0) return;
            if (gridview.SelectedRowsCount > 1) return;
            if (gridview.SelectedRowsCount != 1) return;
            int selectedrowCollectionindex = gridview.GetDataSourceRowIndex(gridview.GetSelectedRows()[0]);
            //TODO Entity Specific Needed here and descritive field
            MaterialEntity gridselected = (MaterialEntity) entityCollectionNonGeneric1[selectedrowCollectionindex];
            if (AskUser.SaveChanges(string.Format("Are you sure to delete this record ?\n Code: {0}", gridselected.MaterialCode)) != DialogResult.Yes) return;
            DataAccessAdapter dataAccessAdapter = new DataAccessAdapter(Cs);
            
            RelationPredicateBucket filter = new RelationPredicateBucket();
            //TODO Delete Filter
            filter.PredicateExpression.Add(MaterialFields.MaterialCode== gridselected.MaterialCode);
            //TODO Entity Specific Needed here
            int deleteEntity = dataAccessAdapter.DeleteEntitiesDirectly("MaterialEntity", filter);
            if (deleteEntity == 1){
                entityCollectionNonGeneric1.RemoveAt(selectedrowCollectionindex);
            }

        }

       







        }

}